import { ref, onMounted } from 'vue'
import type { Ref } from 'vue'
import { Toast } from 'vant'
import { RequestBanner } from '@/api/banner'
import { RequestProductList } from '@/api/product'
import type { IProduct } from '@/types/Types'
import { useRouter } from 'vue-router'
import { RequesetHotProduct} from '@/api/index'
import 'vant/es/toast/style';

interface IBanner {
	id: number
	url: string
	content: string
	number: number
}

/**
 * 轮播业务
 */
export const useBanner = () => {
	const bannerList: Ref<Array<IBanner>> = ref([])
	 //获取轮播banner列表
	const getBannerList = async () => {
		let data = await RequestBanner()
		let { resultCode, resultInfo } = data
		if (resultCode == 1) {
			bannerList.value = resultInfo.list
		}
	}
	onMounted(() => {
		getBannerList()
	})
	return { bannerList }
}

/**
 * 商品列表业务
 */
export const useProductList = () => {
	const loading: Ref<boolean> = ref(false)
	const finished: Ref<boolean> = ref(false)

	let productList: Ref<Array<IProduct>> = ref([])
	let currentNo: number = 1 //当前页号

	const getProductList = async (pageNo: number, pageSize: number) => {
		let data = await RequestProductList(pageNo, pageSize)
		let { resultCode, resultInfo } = data
		if (resultCode == 1) {
			productList.value = productList.value.concat(resultInfo.list)
		}
		// 加载状态结束
		loading.value = false

		if (resultCode == -1) {
			finished.value = true
		}
	}

	/**
	 * 加载更多
	 */
	const onLoad = () => {
		// 第一次加载和组件滚动到底部时，会触发 load 事件并将 loading 设置成 true
		// 注：当数据不在一屏时，会一直触发onLoad
		getProductList(currentNo++, 10)
		// console.log('加载');
		
	}

	/**
	 * 下拉刷新
	 */
	const onRefresh = () => {
		currentNo = 1
		productList.value = []
		setTimeout(() => {
			Toast.success('刷新成功');
			loading.value = false;
		}, 1000);
		getProductList(currentNo, 10)
	}

	return {
		onRefresh,
		onLoad,
		productList,
		loading,
		finished,
	}
}

/**
 * 商品详情
 */
export const useProductDetail = () => {
	const router = useRouter()
	const onDetail = (id: number) => {
		router.push({ path: '/detail/' + id })
	}
	return { onDetail }
}


/**
 * 热门商品
 */
export const useHotProduct = ()=>{
	let hotList = ref([])
	const getHotProduct = ()=>{
		RequesetHotProduct().then(res=>{
			let {resultCode,resultInfo} = res.data
			if(resultCode == 1){
				hotList.value = resultInfo.list
			}
		})
	}
	onMounted(()=>{
		getHotProduct()
	})
	return {hotList}
}
